package com.example.dao.imp;

import com.example.dao.CategoryDao;
import com.example.domain.Category;
import com.example.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class CategoryDaoImp implements CategoryDao {
    @Override
    public List<Category> getAllCategories() {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            return sqlSession.selectList("com.example.dao.CategoryDao.getAllCategories");
        }
    }

    @Override
    public Category getCategoryById(Integer id) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            return sqlSession.selectOne("com.example.dao.CategoryDao.getCategoryById", id);
        }
    }

    @Override
    public void addCategory(Category category) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            sqlSession.insert("com.example.dao.CategoryDao.addCategory", category);
            sqlSession.commit();
        }
    }

    @Override
    public void updateCategory(Category category) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            sqlSession.update("com.example.dao.CategoryDao.updateCategory", category);
            sqlSession.commit();
        }
    }

    @Override
    public void deleteCategory(Integer id) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            sqlSession.delete("com.example.dao.CategoryDao.deleteCategory", id);
            sqlSession.commit();
        }
    }

    @Override
    public List<Category> searchCategoriesByName(String name) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            return sqlSession.selectList("com.example.dao.CategoryDao.searchCategoriesByName", name);
        }
    }
}
